import axios from "axios";
import { put, takeEvery } from "redux-saga/effects";
import { API } from "../../config";
import { Product } from "../../models/product";
import { filterProductAction, filterProductSuccess, filterProductSuccessAction, FILTER_PRODUCT, getProductAction, getProductByIdAction, getProductIdSuccess, getProductSuccess, GET_PRODUCT, GET_PRODUCTBY_ID, searchProductAction, searchProductSuccess, searchProductSuccessAction, SEARCH_PRODUCT } from "../actions/product.action";

interface responseData {
  data: Product[]
}

interface filterResponseData {
  size: number,
  data: Product[]
}

interface getProductByIdResponseData {
  data: Product
}

function* handleGetProduct({sortBy, order, limit}:getProductAction){
  let response:responseData = yield axios.get(`${API}/products`,{params:{
    sortBy,
    order,
    limit
  }})

  yield put(getProductSuccess(response.data,sortBy))
}
function* handleSearchProduct({payload:{category, search}}:searchProductAction) {
  const response:responseData =yield axios.get(`${API}/products/search`,{
    params: {
      category,
      search
    }
  })
  yield put(searchProductSuccess(response.data))
}
function* handleFilterProduct(action:filterProductAction) {
  const {data} = yield axios.post<filterResponseData>(`${API}/products/filter`,action.payload)
  console.log(data)
  yield put(filterProductSuccess(data, action.payload.skip))
}
function* handleGetProductById(action:getProductByIdAction) {
  const {data} = yield axios.get<getProductByIdResponseData>(`${API}/product/${action.payload.productId}`)
  yield put(getProductIdSuccess(data))
}
export default function* productSaga(){
  yield takeEvery(GET_PRODUCT, handleGetProduct)
  yield takeEvery(SEARCH_PRODUCT, handleSearchProduct)
  yield takeEvery(FILTER_PRODUCT, handleFilterProduct)
  yield takeEvery(GET_PRODUCTBY_ID, handleGetProductById)
}